using B.S.XZYData.Api.Read.Application.Command.Permission;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Linq;

namespace B.S.XZYData.Api.Read.Application.Handler.Permission
{
    /// <summary>
    /// 根据ID获取权限处理器
    /// </summary>
    public class GetPermissionByIdHandler : IRequestHandler<GetPermissionByIdCommand, ApiResult<PermissionModel>>
    {
        private readonly IBaseRepository<PermissionModel> permissionRepo;

        public GetPermissionByIdHandler(IBaseRepository<PermissionModel> permissionRepo)
        {
            this.permissionRepo = permissionRepo;
        }

        /// <summary>
        /// 根据ID获取权限详情
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>权限详情</returns>
        public Task<ApiResult<PermissionModel>> Handle(GetPermissionByIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var res = new ApiResult<PermissionModel>();
                var permission = permissionRepo.GetAll().Where(x => !x.IsDeleted && x.Id == request.Id).ToList().FirstOrDefault();
                
                if (permission != null)
                {
                    // 如果有父级权限，获取父级权限名称
                    if (permission.ParentId > 0)
                    {
                        var parentPermission = permissionRepo.GetAll().Where(x => !x.IsDeleted && x.Id == permission.ParentId).ToList().FirstOrDefault();
                        if (parentPermission != null)
                        {
                            permission.ParentName = parentPermission.PermissionName;
                        }
                    }
                    
                    res.Data = permission;
                    res.Msg = "查询权限成功!";
                    res.Code = ApiEnum.Success;
                }
                else
                {
                    res.Data = null;
                    res.Msg = "权限不存在!";
                    res.Code = ApiEnum.Error;
                }
                
                return Task.FromResult(res);
            }
            catch (Exception ex)
            {
                var res = new ApiResult<PermissionModel>();
                res.Data = null;
                res.Msg = "查询权限异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return Task.FromResult(res);
            }
        }
    }
}
